#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>

typedef struct String
{
    int capacity;
    char* ch;
}String;

void TestString();
void StringInit(String* start);
void Strcpy(String* start, char* chars);
bool StrEmpty(String* start);
void ClearString(String* start);
char* Strcat(String* start, char* chars, char* charss);
bool StrCompare(char* chars, char* charss);
char* SubString(String* start, int pos, int want);
int Index(char* chars, char* charss, int pos);

int main()
{
    TestString();
    return 0;
}

void TestString() {
    String* start = (String*)malloc(sizeof(String));
    int want, pos;
    char a[] = "You are wrong!";
    char b[] = "are";
    char b[] = "Never see you again!";
    char* chars = a;
    char* charss = b;

    StringInit(start);
    printf("%s", chars);
    int pos = 3;
    printf("%d", Index(chars, charss, pos));
    /*int len = strlen(chars);
    printf("%d\n", len);*/

    Strcpy(start, chars);
    printf("%s", start->ch);

    /*int Bool = StrEmpty(start);
    printf("%d\n", Bool);*/

    ClearString(start);

    Strcat(start, chars, charss);
    char* newchar = Strcat(start, chars, charss);

    int num = StrCompare(chars, charss);

    char* sub = SubString(start, pos, want);

}


void StringInit(String* start)
{
    assert(start);
    start->capacity = 0;
    start->ch = NULL;
}

void CutOut()
{

}
void replace(char* chars, char* charss, char* rplace)
{

}

int Index(char* chars, char* charss, int pos)
{
    int len = strlen(charss);
    int length = strlen(chars);
    int i = 0;
    char* cur = (char*)malloc(sizeof(char) * len + 1);

    for (int j = 0; j < length - len - 1; j++)
    {
        while (--len >= 0)
        {
            cur[i] = chars[pos];
            i++;
        }
        if (strcmp(cur, charss) == 0)
        {
            return j + pos + 1;
        }
        i = 0;
    }
    return 0;
}

void Strcpy(String* start, char* chars) {
    assert(start);
    int len = strlen(chars);
    start->capacity = len + 1;

    start->ch = (char*)malloc(sizeof(char) * (start->capacity));
    strcpy(start->ch, chars);
    printf("%s\n", start->ch);
}


bool StrEmpty(String* start)
{
    assert(start);
    return start->ch != NULL;
}

void ClearString(String* start)
{
    assert(start);

    int len = start->capacity + 1;
    for (int i = 0; i < len; i++)
    {
        free(start->ch + i);
    }
    start->ch = NULL;
}

char* Strcat(String* start, char* chars, char* charss)
{
    assert(start);

    start->ch = strcat(chars, charss);
    return start->ch;
}

bool StrCompare(char* chars, char* charss)
{
    return strcmp(chars, charss);
}

char* SubString(String* start, int pos, int want)
{
    assert(start);

    char* newnode = (char*)malloc(sizeof(char) * start->capacity);
    for (int i = 0; i < want; i++, pos++)
    {
        newnode[i] = start->ch[pos];
    }
    return newnode;
}
